package wechat.forward.Helper;

import android.content.ContentValues;
import android.database.Cursor;
import android.text.TextUtils;

import java.util.ArrayList;
import java.util.HashMap;


import wechat.forward.Model.ChatRoomMemberModel;
import wechat.forward.Model.FriendModel;
import wechat.forward.Model.GroupModel;

import static de.robv.android.xposed.XposedHelpers.callMethod;
import static de.robv.android.xposed.XposedHelpers.getObjectField;

/**
 * Created by fkzhang on 2/6/2016.
 */
public class WechatMainDBHelper {
    private Object SQLDB;
    private HashMap<String, String> mNicknameCache;
    private HashMap<String, String> mChatroomMemberMap;

    public WechatMainDBHelper(Object dbObject) {
        SQLDB = dbObject;
//        XposedBridge.log("" + dbObject);
        mNicknameCache = new HashMap<>();
    }

    public void insertSQL(String table, String selection, ContentValues contentValues) {
        callMethod(SQLDB, "insert", table, selection, contentValues);
    }

    public Cursor rawQuery(String query) {
        return rawQuery(query, null);
    }

    public void execSQL(String sql) {
        callMethod(getObjectField(SQLDB, "obV"), "execSQL", sql);
    }

    public Cursor rawQuery(String query, String[] args) {
        return (Cursor) callMethod(SQLDB, "rawQuery", query, args);
    }

    public void SQLUpdate(String table, ContentValues contentValues, String selection, String[] args) {
        callMethod(SQLDB, "update", table, contentValues, selection, args);
    }

    public Cursor getMessageBySvrId(String msgSrvId) {
        String sql = "select * from message where msgsvrid=?";
        String[] sqlArgs = {msgSrvId};

        return rawQuery(sql, sqlArgs);
    }

//    public void insertMessage(String talker, int talkerId, String msg) {
//        insertMessage(talker, talkerId, msg, 1, System.currentTimeMillis());
//    }
//
//    public void insertSystemMessage(String talker, int talkerId, String msg) {
//        insertMessage(talker, talkerId, msg, 10000, System.currentTimeMillis());
//    }
//
//    public void insertSystemMessage(String talker, int talkerId, String msg, long createTime) {
//        insertMessage(talker, talkerId, msg, 10000, createTime);
//    }

//    public void insertMessage(String talker, int talkerId, String msg, int type, long createTime) {
//        int status = 3;
//        long msgSvrId = createTime + (new Random().nextInt());
//        long msgId = getNextMsgId();
//        ContentValues v = new ContentValues();
//        v.put("msgid", msgId);
//        v.put("msgSvrid", msgSvrId);
//        v.put("type", type);
//        v.put("status", status);
//        v.put("createTime", createTime);
//        v.put("talker", talker);
//        v.put("content", msg);
//        if (talkerId != -1) {
//            v.put("talkerid", talkerId);
//        }
//        insertSQL("message", "", v);
//    }
//
//    public long getNextMsgId() {
//        Cursor cursor = rawQuery("SELECT max(msgId) FROM message");
//        if (cursor == null || !cursor.moveToFirst())
//            return -1;
//
//        long id = cursor.getInt(0) + 1;
//        cursor.close();
//        return id;
//    }

    //    public Cursor getLastMsg(String username) {
//        String query = "SELECT * FROM message WHERE msgId = (SELECT max(msgId) FROM message WHERE talker='" +
//                username + "')";
//        return rawQuery(query);
//    }
//
//    public int getUnreadCount(String username) {
//        Cursor cursor = rawQuery("select unReadCount from rconversation where " +
//                "username = '" + username
//                + "' and ( parentref is null or parentref = '' ) ");
//
//        if (cursor == null || !cursor.moveToFirst())
//            return 0;
//
//        int cnt = cursor.getInt(cursor.getColumnIndex("unReadCount"));
//        cursor.close();
//        return cnt;
//    }
//
//    public String getNickname(String username) {
//        if (mNicknameCache.containsKey(username)) {
//            return mNicknameCache.get(username);
//        }
//
//        Cursor cursor = getContact(username);
//        if (cursor == null || !cursor.moveToFirst())
//            return username;
//
//        String name = cursor.getString(cursor.getColumnIndex("conRemark"));
//        if (TextUtils.isEmpty(name)) {
//            name = cursor.getString(cursor.getColumnIndex("nickname"));
//        }
//        name = name.trim();
//        cursor.close();
//        mNicknameCache.put(username, name);
//        return name;
//    }
//
    public HashMap<String, String> getChatRoomMembers() {
        String query = "SELECT * FROM chatroom";
        Cursor cursor = rawQuery(query);

        HashMap<String, String> map = new HashMap<>();

        if (cursor == null || !cursor.moveToFirst())
            return map;

        do {
            String memberlist = cursor.getString(cursor.getColumnIndex("memberlist"));
            String displayname = cursor.getString(cursor.getColumnIndex("displayname"));

            String[] members = memberlist.split(";");
            String[] names;
            if (displayname.contains("、")) {
                names = displayname.split("、");
            } else {
                names = displayname.split(",");
            }
            int size = members.length > names.length ? names.length : members.length;
            for (int i = 0; i < size; i++) {
                map.put(members[i].trim(), names[i].trim());
            }

        } while (cursor.moveToNext());
        cursor.close();

        return map;
    }

//    public String getChatroomName(String username) {
//        String name = getNickname(username);
//        if (!TextUtils.isEmpty(name))
//            return name;
//
//        String query = "SELECT * FROM chatroom WHERE chatroomname = ?";
//        Cursor cursor = rawQuery(query, new String[]{username});
//        if (cursor == null || !cursor.moveToFirst())
//            return null;
//
//        name = cursor.getString(cursor.getColumnIndex("displayname"));
//        cursor.close();
//        return name;
//    }

    public String getChatroomMemberName(String id) {
        if (mChatroomMemberMap == null) {
            mChatroomMemberMap = getChatRoomMembers();
        }

        if (mChatroomMemberMap.containsKey(id)) {
            return mChatroomMemberMap.get(id);
        }

        // reload
        mChatroomMemberMap = getChatRoomMembers();
        if (mChatroomMemberMap.containsKey(id)) {
            return mChatroomMemberMap.get(id);
        }
        return null;
    }

    private Cursor getContact(String username) {
        String query = "SELECT * FROM rcontact WHERE username = ?";
        return rawQuery(query, new String[]{username});
    }

    public HashMap<String, String> getChatRoomMap() {
        String query = "SELECT * FROM rcontact WHERE username like '%@chatroom';";
        Cursor cursor = rawQuery(query);
        HashMap<String, String> map = new HashMap<>();
        if (cursor == null || !cursor.moveToFirst())
            return map;
        do {
            String username = cursor.getString(cursor.getColumnIndex("username"));
            String nickname = cursor.getString(cursor.getColumnIndex("nickname"));
            if (TextUtils.isEmpty(nickname)) {
                nickname = getDisplayNameInChatRoomTable(username);
            }
            if (TextUtils.isEmpty(nickname)) {
                nickname = "";
            }
            map.put(username, nickname);
        } while (cursor.moveToNext());
        cursor.close();
        return map;
    }

    private String getDisplayNameInChatRoomTable(String id) {
        String query = "SELECT * FROM chatroom WHERE chatroomname = " + id + ";";
        Cursor cursor = rawQuery(query);
        if (cursor == null || !cursor.moveToFirst()) {
            return null;
        }
        HashMap<String, String> map = new HashMap<>();
        do {
            String displayname = cursor.getString(cursor.getColumnIndex("displayname"));
            if (!TextUtils.isEmpty(displayname)) {
                if (displayname.length() > 10) {
                    displayname = displayname.substring(0, 10);
                    return displayname;
                }
            }
        } while (cursor.moveToNext());
        return null;
    }

    public String getUserNickName(String id) {
        String name = getFriendUserName(id);
        if (name == null) {
            name = getChatroomMemberName(id);
        }
        return name;
    }

    public String getUserId(String name) {
        if (mChatroomMemberMap == null) {
            mChatroomMemberMap = getChatRoomMembers();
        }
        for (HashMap.Entry<String, String> entry : mChatroomMemberMap.entrySet()) {
            if (isTheSamePerson(entry.getValue(), name)) {
                return entry.getKey();
            }
        }
        mChatroomMemberMap = getChatRoomMembers();
        for (HashMap.Entry<String, String> entry : mChatroomMemberMap.entrySet()) {
            if (isTheSamePerson(entry.getValue(), name)) {
                return entry.getKey();
            }
        }
        return null;
    }

    private static boolean isTheSamePerson(String name, String luckMoneyName) {
        if (TextUtils.isEmpty(luckMoneyName) || TextUtils.isEmpty(name)) {
            return false;
        }
        if (luckMoneyName.endsWith("...")) {
            luckMoneyName = luckMoneyName.substring(0, luckMoneyName.indexOf("..."));
            return name.startsWith(luckMoneyName);
        } else {
            return luckMoneyName.equals(name);
        }
    }

    private String getFriendUserName(String id) {
        String name;
        Cursor cursor = getContact(id);
        if (cursor == null || !cursor.moveToFirst())
            return null;
        name = cursor.getString(cursor.getColumnIndex("nickname"));
        if (name != null) {
            name = name.trim();
        }
        cursor.close();
        return name;
    }

    private String getChatRoomMemberById(String id, String room) {
        String query = "SELECT * FROM chatroom WHERE chatroomname = ?";
        Cursor cursor = rawQuery(query, new String[]{room});
        if (cursor == null || !cursor.moveToFirst()) {
            return null;
        }
        HashMap<String, String> map = new HashMap<>();
        do {
            String memberlist = cursor.getString(cursor.getColumnIndex("memberlist"));
            String displayname = cursor.getString(cursor.getColumnIndex("displayname"));
            String[] members = memberlist.split(";");
            String[] names;
            if (displayname.contains("、")) {
                names = displayname.split("、");
            } else {
                names = displayname.split(",");
            }
            int size = members.length > names.length ? names.length : members.length;
            for (int i = 0; i < size; i++) {
                map.put(members[i].trim(), names[i].trim());
            }
        } while (cursor.moveToNext());
        cursor.close();
        if (map.containsKey(id)) {
            return map.get(id);
        } else {
            return null;
        }
    }

    /**
     * @param room
     * @return id-name
     */
    private HashMap<String, String> getChatRoomMember(String room) {
        String query = "SELECT * FROM chatroom WHERE chatroomname = ?";
        Cursor cursor = rawQuery(query, new String[]{room});
        if (cursor == null || !cursor.moveToFirst()) {
            return new HashMap<>();
        }
        HashMap<String, String> map = new HashMap<>();
        do {
            String memberlist = cursor.getString(cursor.getColumnIndex("memberlist"));
            String displayname = cursor.getString(cursor.getColumnIndex("displayname"));
            String[] members = memberlist.split(";");
            String[] names;
            if (displayname.contains("、")) {
                names = displayname.split("、");
            } else {
                names = displayname.split(",");
            }
            int size = members.length > names.length ? names.length : members.length;
            for (int i = 0; i < size; i++) {
                map.put(members[i].trim(), names[i].trim());
            }
        } while (cursor.moveToNext());
        cursor.close();
        return map;
    }

    /**
     * id-name
     *
     * @return
     */
    public HashMap<String, String> getFriends() {
        String query = "select * ,rowid from rcontact  where (type & 1!=0) and type & 32=0  and type & 8 =0  and verifyFlag & 8 =0  and ( username not like '%@%' or (( (type & 1!=0) and type & 8=0 and username like '%@talkroom'))) and username != 'googlecontact' and username != 'appbrandcustomerservicemsg' and username != 'notifymessage' and username != 'weibo' and username != 'pc_share' and username != 'officialaccounts' and username != 'voicevoipapp' and username != 'cardpackage' and username != 'qqfriend' and username != 'helper_entry' and username != 'medianote' and username != 'shakeapp' and username != 'qmessage' and username != 'voipapp' and username != 'qqmail' and username != 'qqsync' and username != 'blogapp' and username != 'lbsapp' and username != 'feedsapp' and username != 'readerapp' and username != 'newsapp' and username != 'floatbottle' and username != 'fmessage' and username != 'tmessage' and username != 'facebookapp' and username != 'meishiapp' and username != 'masssendapp' and username != 'voiceinputapp' and username != 'filehelper' and username != 'linkedinplugin' order by showHead asc,  case when length(conRemarkPYFull) > 0 then upper(conRemarkPYFull)  else upper(quanPin) end asc,  case when length(conRemark) > 0 then upper(conRemark)  else upper(quanPin) end asc,  upper(quanPin) asc,  upper(nickname) asc,  upper(username) asc";
        Cursor cursor = rawQuery(query);
        HashMap<String, String> map = new HashMap<>();
        if (cursor == null || !cursor.moveToFirst())
            return map;
        do {
            String username = cursor.getString(cursor.getColumnIndex("username"));
            String nickname = cursor.getString(cursor.getColumnIndex("nickname"));
            if (TextUtils.isEmpty(nickname)) {
                nickname = "";
            }
            map.put(username, nickname);
        } while (cursor.moveToNext());
        cursor.close();
        return map;
    }

    public ArrayList<FriendModel> getFriendsModel() {
        String query = "select * ,rowid from rcontact  where (type & 1!=0) and type & 32=0  and type & 8 =0  and verifyFlag & 8 =0  and ( username not like '%@%' or (( (type & 1!=0) and type & 8=0 and username like '%@talkroom'))) and username != 'googlecontact' and username != 'appbrandcustomerservicemsg' and username != 'notifymessage' and username != 'weibo' and username != 'pc_share' and username != 'officialaccounts' and username != 'voicevoipapp' and username != 'cardpackage' and username != 'qqfriend' and username != 'helper_entry' and username != 'medianote' and username != 'shakeapp' and username != 'qmessage' and username != 'voipapp' and username != 'qqmail' and username != 'qqsync' and username != 'blogapp' and username != 'lbsapp' and username != 'feedsapp' and username != 'readerapp' and username != 'newsapp' and username != 'floatbottle' and username != 'fmessage' and username != 'tmessage' and username != 'facebookapp' and username != 'meishiapp' and username != 'masssendapp' and username != 'voiceinputapp' and username != 'filehelper' and username != 'linkedinplugin' order by showHead asc,  case when length(conRemarkPYFull) > 0 then upper(conRemarkPYFull)  else upper(quanPin) end asc,  case when length(conRemark) > 0 then upper(conRemark)  else upper(quanPin) end asc,  upper(quanPin) asc,  upper(nickname) asc,  upper(username) asc";
//        String query = "select * from rcontact where type & 1 !=0 and type & 32 =0 and type & 8 =0 and verifyFlag & 8 = 0 and ( username not like '%@%') and rcontact.username != 'qqmail' and rcontact.username != 'fmessage' and rcontact.username != 'tmessage' and rcontact.username != 'qmessage' and rcontact.username != 'qqsync' and rcontact.username != 'floatbottle' and rcontact.username != 'lbsapp' and rcontact.username != 'shakeapp' and rcontact.username != 'medianote' and rcontact.username != 'qqfriend' and rcontact.username != 'newsapp' and rcontact.username != 'blogapp' and rcontact.username != 'facebookapp' and rcontact.username != 'masssendapp' and rcontact.username != 'feedsapp' and rcontact.username != 'voipapp' and rcontact.username != 'cardpackage' and rcontact.username != 'voicevoipapp' and rcontact.username != 'voiceinputapp' and rcontact.username != 'officialaccounts' and rcontact.username != 'googlecontact' and rcontact.username != 'linkedinplugin' and rcontact.username != 'notifymessage' and rcontact.username != 'wxid_98g2e4pnayek22' and rcontact.username != 'weixin' and rcontact.username != 'helper_entry' and rcontact.username != 'filehelper' or username = 'weixin'";
        Cursor cursor = rawQuery(query);
        ArrayList<FriendModel> list = new ArrayList<>();
        if (cursor == null || !cursor.moveToFirst())
            return list;
        do {
            FriendModel friendModel = new FriendModel();
            friendModel.mainId = cursor.getString(cursor.getColumnIndex("username"));
            friendModel.secondId = cursor.getString(cursor.getColumnIndex("alias"));
            friendModel.pyInitial = cursor.getString(cursor.getColumnIndex("pyInitial"));
            friendModel.userName = cursor.getString(cursor.getColumnIndex("nickname"));
            list.add(friendModel);
        } while (cursor.moveToNext());
        cursor.close();
        return list;
    }

    public ArrayList<GroupModel> getGroupsModel() {
        String query = "SELECT * FROM rcontact WHERE username like '%@chatroom';";
        Cursor cursor = rawQuery(query);
        ArrayList<GroupModel> list = new ArrayList<>();
        if (cursor == null || !cursor.moveToFirst())
            return list;
        do {
            GroupModel groupModel = new GroupModel();
            groupModel.mainId = cursor.getString(cursor.getColumnIndex("username"));
            groupModel.pyInitial = cursor.getString(cursor.getColumnIndex("pyInitial"));
            groupModel.userName = cursor.getString(cursor.getColumnIndex("nickname"));
            list.add(groupModel);
        } while (cursor.moveToNext());
        cursor.close();
        return list;
    }

    /**
     * id-name
     *
     * @return
     */
    public ArrayList<ChatRoomMemberModel> getAllChatRoomMembers() {
        String query = "SELECT * FROM chatroom";
        Cursor cursor = rawQuery(query);
        if (cursor == null || !cursor.moveToFirst()) {
            return null;
        }
        ArrayList<ChatRoomMemberModel> list = new ArrayList<>();
        do {
            String chatRoomId = cursor.getString(cursor.getColumnIndex("chatroomname"));
            String memberlist = cursor.getString(cursor.getColumnIndex("memberlist"));
            String displayname = cursor.getString(cursor.getColumnIndex("displayname"));
            String[] members = memberlist.split(";");
            String[] names;
            if (displayname.contains("、")) {
                names = displayname.split("、");
            } else {
                names = displayname.split(",");
            }
            int size = members.length > names.length ? names.length : members.length;
            for (int i = 0; i < size; i++) {
                ChatRoomMemberModel chatRoomMemberModel = new ChatRoomMemberModel();
                chatRoomMemberModel.chatRoomId = chatRoomId;
                chatRoomMemberModel.userId = members[i];
                chatRoomMemberModel.userName = names[i];
                list.add(chatRoomMemberModel);
            }
        } while (cursor.moveToNext());
        cursor.close();
        return list;
    }

    public void deleteMsg(long msgId) {
        String sql = "DELETE FROM message WHERE msgId = '" + msgId + "'";
        execSQL(sql);
    }
}